package com.wnhz.work.yz.fragment.install;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.activity.InstallAllActivity;
import com.wnhz.work.yz.activity.InstallDetailsActivity;
import com.wnhz.work.yz.activity.PaySuccessActivity;
import com.wnhz.work.yz.activity.Wuliu2Activity;
import com.wnhz.work.yz.alipay.PayResult;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.ALiBean;
import com.wnhz.work.yz.bean.AllInstallBean;
import com.wnhz.work.yz.bean.GoToOrderBean;
import com.wnhz.work.yz.bean.InstallDetailsBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by admin on 2017/6/2.
 */
public class InstallFragment0 extends Fragment {
    private View view;
    private InstallAllActivity activity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_install, container, false);
        activity = (InstallAllActivity) getActivity();
        //   upload("0");
        return view;
    }

    private RecyclerView recyclerView;
    private BaseRVAdapter adapter;

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
        upLoad();
        super.onActivityCreated(savedInstanceState);
    }

    private List<AllInstallBean.InfoEntity> info1 = new ArrayList<>();

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", 0);
        activity.showDialog();
        XUtil.Post(Url.DECORATE_DECORATEORDERLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        AllInstallBean bean = gson.fromJson(result, AllInstallBean.class);
                        info1 = bean.getInfo();
                        setData();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();
            }
        });


    }

    private void setData() {
        adapter = new BaseRVAdapter(activity, info1) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_install_fragment;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                holder.setTextView(R.id.price, info1.get(position).getAmount());


                holder.setTextView(R.id.order_num, info1.get(position).getOrder_no());
                holder.setTextView(R.id.creat_time, info1.get(position).getCreate_time());
                //0已取消 1待付款 2待接单 3待安装 4安装中 5待验收 6验收完成 7整改中 8整改完待验收
                switch (Integer.parseInt(info1.get(position).getStatus())) {
                    case 0:
                        holder.setTextView(R.id.status, "已取消");
                        holder.getView(R.id.status0).setVisibility(View.GONE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.VISIBLE);
                        holder.getView(R.id.gotopay).setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        holder.setTextView(R.id.status, "待付款");
                        holder.getView(R.id.status0).setVisibility(View.VISIBLE);
                        holder.getView(R.id.look_progress).setVisibility(View.GONE);
                        holder.getView(R.id.quxiao).setVisibility(View.VISIBLE);
                        holder.getView(R.id.gotopay).setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        holder.setTextView(R.id.status, "待接单");
                        holder.getView(R.id.status0).setVisibility(View.GONE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.VISIBLE);
                        holder.getView(R.id.gotopay).setVisibility(View.VISIBLE);
                        break;
                    case 3:
                        holder.setTextView(R.id.status, "待安装");
                        holder.getView(R.id.status0).setVisibility(View.GONE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.VISIBLE);
                        holder.getView(R.id.gotopay).setVisibility(View.VISIBLE);
                        break;
                    case 4:
                        holder.setTextView(R.id.status, "安装中");
                        holder.getView(R.id.status0).setVisibility(View.VISIBLE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.GONE);
                        holder.getView(R.id.gotopay).setVisibility(View.GONE);
                        break;
                    case 5:
                        holder.setTextView(R.id.status, "待验收");
                        holder.getView(R.id.status0).setVisibility(View.VISIBLE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.GONE);
                        holder.getView(R.id.gotopay).setVisibility(View.GONE);
                        break;
                    case 6:
                        holder.setTextView(R.id.status, "验收完成");
                        holder.getView(R.id.status0).setVisibility(View.VISIBLE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.GONE);
                        holder.getView(R.id.gotopay).setVisibility(View.GONE);
                        break;
                    case 7:
                        holder.setTextView(R.id.status, "整改中");
                        holder.getView(R.id.status0).setVisibility(View.VISIBLE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.GONE);
                        holder.getView(R.id.gotopay).setVisibility(View.GONE); break;
                    case 8:
                        holder.setTextView(R.id.status, "整改完待验收");
                        holder.getView(R.id.status0).setVisibility(View.VISIBLE);
                        holder.getView(R.id.look_progress).setVisibility(View.VISIBLE);
                        holder.getView(R.id.quxiao).setVisibility(View.GONE);
                        holder.getView(R.id.gotopay).setVisibility(View.GONE);break;

                }

                RecyclerView shop = holder.getView(R.id.shop);
                shop.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
                shop.setAdapter(new BaseRVAdapter(activity, info1.get(position).getOrderdetail()) {
                    @Override
                    public int getLayoutId(int viewType) {
                        return R.layout.item_order;
                    }

                    @Override
                    public void onBind(BaseViewHolder holder, int position2) {
                        x.image().bind(holder.getImageView(R.id.img), info1.get(position).getOrderdetail().get(position2).getGoods_img());
                        holder.setTextView(R.id.title, info1.get(position).getOrderdetail().get(position2).getGoods_name());
                        holder.setTextView(R.id.type, info1.get(position).getOrderdetail().get(position2).getGoods_name());
                        holder.setTextView(R.id.area, info1.get(position).getOrderdetail().get(position2).getGoods_des());
                        holder.setTextView(R.id.num, "x" + info1.get(position).getOrderdetail().get(position2).getNums() + "/" + info1.get(position).getOrderdetail().get(position2).getUnit());
                        holder.setTextView(R.id.price, "￥" + info1.get(position).getOrderdetail().get(position2).getPrice());
                        holder.getView(R.id.ll_max).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // startActivity(new Intent(activity, Wuliu2Activity.class).putExtra("budget_id", info1.get(position).getId()).putExtra("isUp", 1));
                                getDetails(info1.get(position).getOrderid());

                            }
                        });
                    }
                });
                //查看进度
                holder.getView(R.id.look_progress).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(activity, Wuliu2Activity.class).putExtra("budget_id", info1.get(position).getOrderid()));
                    }
                });

                //取消安装
                holder.getView(R.id.quxiao).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        upLoad(info1.get(position).getOrderid(), position);
                    }
                });
//                //上传进度
//                holder.getView(R.id.up_progress).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        startActivity(new Intent(activity, Wuliu2Activity.class).putExtra("budget_id", info1.get(position).getId()).putExtra("isUp", 1));
//                    }
//                });
                //详情
                holder.getView(R.id.ll_max).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // startActivity(new Intent(activity, Wuliu2Activity.class).putExtra("budget_id", info1.get(position).getId()).putExtra("isUp", 1));
                        getDetails(info1.get(position).getOrderid());

                    }
                });

                holder.getView(R.id.gotopay).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        activity.MyToast("支付");
                        pay = 1;
                        getAllInfo(info1.get(position).getOrderid(), info1.get(position).getType());

                    }
                });
            }
        };
        recyclerView.setAdapter(adapter);

    }

    private void getDetails(String orderid) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", orderid);
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----xq" + key, "" + value + "\n");
            }
        }
        activity.showDialog();
        XUtil.Post(Url.DECORATE_DECORATEORDERDETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    super.onSuccess(result);
                    if ("1".equals(res)) {
//                        activity.MyToast(info);
                        Gson gson=new Gson();
                        InstallDetailsBean bean=gson.fromJson(result,InstallDetailsBean.class);
                        InstallDetailsBean.InfoEntity info2 = bean.getInfo();
                        startActivity(new Intent(activity,InstallDetailsActivity.class).putExtra("info2",info2));
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();

            }
        });
    }

    private GoToOrderBean.InfoEntity info9 = new GoToOrderBean.InfoEntity();

    private void getAllInfo(String order_no, String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", order_no);
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----zf" + key, "" + value + "\n");
            }
        }
        XUtil.Post(Url.DECORATE_ORDERPAY, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    Log.e("----", "onSuccess:= " + info);
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        GoToOrderBean bean = gson.fromJson(result, GoToOrderBean.class);
                        info9 = bean.getInfo();
                        //startActivity(new Intent(activity, GotoOrderActivity.class).putExtra("info1", info1));
                        tan(info9);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });


    }

    private int pay = 1;
    private static final int TOALIPAY = 3;
    private static final int SDK_PAY_FLAG = 1;

    private void tan(final GoToOrderBean.InfoEntity info9) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        View view = View.inflate(activity, R.layout.dialog_pay3, null);
        builder.setView(view);

        //
        final AlertDialog show = builder.show();

        Window dialogWindow = show.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);

        dialogWindow.setAttributes(lp);
        //
        TextView pay_money = (TextView) view.findViewById(R.id.pay_money);
        pay_money.setText("" + info9.getNeedPay() + "元");
        TextView yue_pay_info = (TextView) view.findViewById(R.id.yue_pay_info);
        TextView ali_pay_info = (TextView) view.findViewById(R.id.ali_pay_info);
        try {
            Double.parseDouble(info9.getWallet());
            yue_pay_info.setText("(账户余额" + info9.getWallet() + "元)");
        } catch (Exception e) {
            yue_pay_info.setText("(账户余额" + info9.getWallet() + ")");
        }
        String m = "支付宝许支付<font color=\"#e9573d\">" + info9.getNeedPay() + "</font>元";
        ali_pay_info.setText(Html.fromHtml(m));

        final ImageView ali_img = (ImageView) view.findViewById(R.id.ali_img);
        final ImageView yue_img = (ImageView) view.findViewById(R.id.yue_img);
        view.findViewById(R.id.ll_ali2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ali_img.setImageResource(R.mipmap.ic_choose_li);
                yue_img.setImageResource(R.mipmap.ic_choose_nor);
                pay = 1;
            }
        });
        view.findViewById(R.id.ll_yue2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yue_img.setImageResource(R.mipmap.ic_choose_li);
                ali_img.setImageResource(R.mipmap.ic_choose_nor);
                pay = 2;
            }
        });
        view.findViewById(R.id.submit_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                show.dismiss();
                String url = "";
                if (pay == 1) {
                    //  MyToast("支付宝");
                    url = Url.DECORATE_ALIPAY;
                } else {
                    // MyToast("余额");
                    url = Url.DECORATE_WALLETPAY;
                }
                Map<String, Object> map = new HashMap<>();
                map.put("token", MyApplication.getInstance().getUserBean().getToken());
                map.put("order_no", info9.getOrder_no());
                activity.showDialog();
                XUtil.Post(url, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Log.i("----", "onSuccess:= " + result);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            String res = jsonObject.optString("result");
                            String info = jsonObject.optString("info");
                            Log.e("----", "onSuccess:= " + info);
                            if ("1".equals(res)) {
                                if (pay == 1) {
                                    Gson gson = new Gson();
                                    ALiBean bean = gson.fromJson(result, ALiBean.class);
                                    if ("1".equals(bean.getResult())) {
                                        Message msg2 = Message.obtain();
                                        msg2.what = TOALIPAY;
                                        msg2.obj = bean.getInfo();
                                        mHandler.sendMessage(msg2);
                                    }
                                } else {
                                    setStart(info9.getOrder_no(), info9.getNeedPay());
                                }
                            } else {
                                if ("-1".equals(res)) {
                                    info = "请重新登录";
                                }
                                activity.MyToast(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFinished() {
                        activity.closeDialog();
                        super.onFinished();
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        activity.closeDialog();
                        ex.printStackTrace();
                    }
                });


            }
        });

        //


    }

    private void setStart(String str_number, String price) {
        Intent intent = new Intent(activity, PaySuccessActivity.class);
        //   Log.e("----",infos.optString("order_no"));
        intent.putExtra("str_number", str_number);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        intent.putExtra("str_tiem", df.format(new Date()));
        intent.putExtra("str_price", price);
        startActivity(intent);
    }

    public void payV2(ALiBean.InfoEntity info) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        final String orderinfo = "_input_charset=\"" + info.get_input_charset() + "\"&body=\"" + info.getBody() + "\"&notify_url=\"" + info.getNotify_url() + "\"&out_trade_no=\"" + info.getOut_trade_no() + "\"&partner=\"" + info.getPartner() + "\"&payment_type=\"" + info.getPayment_type() + "\"&seller_id=\"" + info.getSeller_id() + "\"&service=\"" + info.getService() + "\"&subject=\"" + info.getSubject() + "\"&total_fee=\"" + info.getTotal_fee() + "\"&sign=\"" + info.getSign() + "\"&sign_type=\"" + info.getSign_type() + "\"";

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    //   Log.e("-----", resultInfo + "---" + resultStatus);
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(activity, "支付成功", Toast.LENGTH_SHORT).show();
                        //  setStart(budget_no, pay_money, pay_type);
                        setStart(info9.getOrder_no(), info9.getNeedPay());

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(activity, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                case TOALIPAY: {
                    ALiBean.InfoEntity obj = (ALiBean.InfoEntity) msg.obj;
                    payV2(obj);
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    private void upLoad(String id, final int pos) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("orderid", id);
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----qx" + key, "" + value + "\n");
            }
        }
        activity.showDialog();
        XUtil.Post(Url.DECORATE_CANCLEDECORATEORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    super.onSuccess(result);
                    if ("1".equals(res)) {
                        activity.MyToast(info);
                        info1.get(pos).setStatus("0");
                        adapter.notifyDataSetChanged();
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        activity.MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                activity.closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                activity.closeDialog();
                ex.printStackTrace();

            }
        });


    }

}
